package com.erlinyou.im.web.config.session;

import java.util.HashMap;
import java.util.Map;

import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;

public class SessionIndexMap {
	private static final Map<Object, Map<String,Session>> sessionsIndex = new HashMap<>();
	public static Session put(Object attributeValue,Session session){
		Map<String, Session> sessionMap = sessionsIndex.get(attributeValue);
		if(sessionMap == null){
			sessionMap = new HashMap<>();
			sessionsIndex.put(attributeValue, sessionMap);
		}
		return sessionMap.put(session.getId(), session);
	}
	
	public static void remove(Session session){
		String attributeValue = session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
		if(attributeValue!=null){
			Map<String, Session> sessionMap = sessionsIndex.get(attributeValue);
			if(sessionMap!=null){
				sessionMap.remove(session.getId());
				if(sessionMap.size() == 0){
					sessionsIndex.remove(attributeValue);
				}
			}
		}
	}
	
	public static Map<String,Session> get(Object attributeValue){
		return sessionsIndex.get(attributeValue);
	}
}
